package com.cjd.common.rx;

import com.cjd.common.bean.BaseBean;
import com.cjd.common.preferences.UserPreference;
import com.cjd.common.utils.LogUtils;

import org.jetbrains.annotations.NotNull;

import java.net.ConnectException;
import java.net.HttpURLConnection;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Author 陈积东
 * Email @email 374122600@qq.com
 * Created by 2021/3/4
 * Desc
 */
public abstract class BaseObserver<T extends BaseBean> implements Observer<T> {

    @Override
    public void onSubscribe(@NotNull Disposable d) {
        onStart();
    }

    @Override
    public void onNext(@NotNull T t) {
        if (t.getCode() != null && t.getCode() == 0)
            onSuccess(t);
        else {
            onError(t.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        onComplete();
        if (e instanceof HttpException) {
            int code = ((HttpException) e).code();
            switch (code) {
                case HttpURLConnection.HTTP_UNAUTHORIZED:
                    UserPreference.INSTANCE.logout();
                    onError("身份证验证失败请重新登录");
                    break;
                case HttpURLConnection.HTTP_INTERNAL_ERROR:
                    onError("系统繁忙！");
                    break;
            }
        } else if (e instanceof ConnectException) {
            onError("网络错误！请检查网络是否通畅");
        } else {
            LogUtils.e(e);
            onError("系统异常！");
        }

    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(@NotNull T t);

    /**
     * 自定义 处理 http code ！= 200 情况
     */
    public void onError(String msg) {

    }

    public void onStart() {

    }
}
